package com.reshare.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.reshare.base.BaseService;
import com.reshare.bean.Seek;
import com.reshare.bean.User;
import com.reshare.mapper.SeekMapper;
import com.reshare.query.SeekQuery;
import com.reshare.utils.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SeekService extends BaseService<Seek, Integer> {

    @Resource
    private SeekMapper seekMapper;

    /**
     * 求购信息查询
     */
    public Map<String, Object> querySeekByParams(SeekQuery query) {
        //条件查询
        List<Seek> slist = seekMapper.selectByParam(query);
        //设置分页
        PageHelper.startPage(query.getPage(), query.getLimit());
        PageInfo<Seek> plist = new PageInfo<>(slist);

        //实例化Map
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "success");
        map.put("count", plist.getTotal());
        map.put("data", plist.getList());
        //返回数据
        return map;
    }


    /**
     * 添加信息
     */
    public void saveSeek(Seek seek) {
        System.out.println(seek);
        //判断信息是否为空
        checkSeek(seek.getTitle(), seek.getMinPrice(), seek.getMinPrice());
        //修改默认值
        Date newTime = new Date();
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        seek.setPublishDate(date.format(newTime));
        seek.setState(1);

        //判断是否添加成功
        AssertUtil.isTrue(seekMapper.insertSelective(seek) < 1, "添加失败，请重试");

    }


    /**
     * 检查方法
     *
     * @param Title
     * @param minPrice
     * @param maxPrice
     */
    private void checkSeek(String Title, Double minPrice, Double maxPrice) {

        //判断输入的标题是否为空
        AssertUtil.isTrue(StringUtils.isBlank(Title), "请输入求购标题");
        //判断输入价格是否为空
        AssertUtil.isTrue(StringUtils.isBlank(minPrice.toString()), "请输入最低价格");
        AssertUtil.isTrue(StringUtils.isBlank(maxPrice.toString()), "请输入最高价格");
        //判断最小价格是否小于最大价格
        AssertUtil.isTrue(minPrice<maxPrice,"最小值应小于最大值");

    }


}
